package com.example.ttkl;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.example.ttkl.Base.BaseActivity;
import com.example.ttkl.adapter.HomeVPTabAdapter;
import com.example.ttkl.bean.GiteeCommitsBean;
import com.example.ttkl.bean.TextBean;
import com.example.ttkl.fragment.XgjFragment;
import com.example.ttkl.fragment.XyxFragment;
import com.example.ttkl.interfaces.IHome;
import com.example.ttkl.presenter.HomePresenter;
import com.example.ttkl.util.HomeProgressDialog;
import com.example.ttkl.util.SpUtils;
import com.example.ttkl.util.SystemUtils;
import com.kc.openset.ad.banner.OSETBanner;
import com.kc.openset.ad.banner.OSETBannerAd;
import com.kc.openset.ad.intestitial.OSETInterstitial;
import com.kc.openset.ad.intestitial.OSETInterstitialAd;
import com.kc.openset.ad.listener.OSETBannerAdLoadListener;
import com.kc.openset.ad.listener.OSETBannerListener;
import com.kc.openset.ad.listener.OSETInterstitialAdLoadListener;
import com.kc.openset.ad.listener.OSETInterstitialListener;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.request.BaseRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity<IHome.MainPersenter> implements IHome.MainView, View.OnClickListener {

    private MainActivity mContext;
    private ViewPager2 mVP;
    private LinearLayout mLLXGJ, mLLXYX;
    private ImageView mIvXGJ, mIvXYX, mIvCurrent;
    private TextView mTvXGJ, mTvXYX, mTvCurrent;
    private AlertDialog alertDialog;//更新升级弹窗
    private FrameLayout flBanner;


    @Override
    protected IHome.MainPersenter initPresenter() {
        return new HomePresenter();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        mContext = this;
        mVP = findViewById(R.id.viewPager);
        mLLXGJ = findViewById(R.id.ll_xgj);
        mLLXYX = findViewById(R.id.ll_xyx);
        mIvXGJ = findViewById(R.id.iv_xgj);
        mIvXYX = findViewById(R.id.iv_xyx);
        mTvXGJ = findViewById(R.id.tv_xgj);
        mTvXYX = findViewById(R.id.tv_xyx);
        flBanner = findViewById(R.id.fl);
        mLLXGJ.setOnClickListener(this);
        mLLXYX.setOnClickListener(this);
        mIvXGJ.setSelected(true);
        mTvXGJ.setSelected(true);
        mIvCurrent = mIvXGJ;
        mTvCurrent = mTvXGJ;
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(new XgjFragment());
        fragments.add(new XyxFragment());
        ArrayList<TextBean> textBeans = new ArrayList<>();
        textBeans.add(new TextBean("小工具", true));
        textBeans.add(new TextBean("小游戏", false));
        HomeVPTabAdapter homeVPTabAdapter = new HomeVPTabAdapter(getSupportFragmentManager(), getLifecycle(), fragments, textBeans);
        mVP.setAdapter(homeVPTabAdapter);
        mVP.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                //正在滚动，滑动
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
        int ttklyszc = SpUtils.getInstance().getInt("ttklyszc");
        if (ttklyszc != 1){
            onDialog();
        }
        requestManagerPermission();
    }

    @Override
    protected void initData() {
        mPresenter.getCommits();
    }

    @Override
    protected void initListener() {

    }

    private void changeTab(int position) {
        mIvCurrent.setSelected(false);
        mTvCurrent.setSelected(false);
        switch (position) {
            case R.id.ll_xgj:
                mVP.setCurrentItem(0);
            case 0:
                mIvXGJ.setSelected(true);
                mTvXGJ.setSelected(true);
                mIvCurrent = mIvXGJ;
                mTvCurrent = mTvXGJ;
                flBanner.removeAllViews();
                showBanner();
                break;
            case R.id.ll_xyx:
                mVP.setCurrentItem(1);
            case 1:
                mIvXYX.setSelected(true);
                mTvXYX.setSelected(true);
                mIvCurrent = mIvXYX;
                mTvCurrent = mTvXYX;
                showInsert();
                break;
        }
    }

    public void onDialog(){

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        AlertDialog alertDialog1 = builder.create();
        alertDialog1.show();
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_yinsizhengce, null);
        alertDialog1.setContentView(inflate);
        alertDialog1.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog1.setCanceledOnTouchOutside(false);
        TextView mTv_Ty = inflate.findViewById(R.id.tv_ty);
        TextView mTv_Bty = inflate.findViewById(R.id.tv_bty);
        mTv_Ty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpUtils.getInstance().setValue("ttklyszc",1);
                alertDialog1.dismiss();
            }
        });
        mTv_Bty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
                finishAffinity();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAndRemoveTask();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        changeTab(v.getId());
    }

    @Override
    public void showTips(String tips) {

    }

    @Override
    public void showLoading(int visble) {

    }

    private OSETBannerAd mOSETBannerAd;

    private void destroyBanner() {
        flBanner.removeAllViews();
        if (mOSETBannerAd != null) {
            mOSETBannerAd.destroy();
            mOSETBannerAd = null;
        }
    }

    private void showBanner() {
        OSETBanner.getInstance()
                .setContext(mContext)
                .setPosId(Common.POS_ID_BANNER)
                .loadAd(new OSETBannerAdLoadListener() {
                    @Override
                    public void onLoadSuccess(OSETBannerAd osetBannerAd) {
                        mOSETBannerAd = osetBannerAd;
                        osetBannerAd.render(mContext, new OSETBannerListener() {
                            @Override
                            public void onClick(View view) {
                                Toast.makeText(mContext, "onClick", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onClose(View view) {
                                destroyBanner();
                                Toast.makeText(mContext, "onClose", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onRenderSuccess(View view) {
                                Toast.makeText(mContext, "onLoad", Toast.LENGTH_SHORT).show();
                                flBanner.removeAllViews();
                                flBanner.addView(view);
                            }

                            @Override
                            public void onShow(View view) {
                                Toast.makeText(mContext, "onShow", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(String s, String s1) {
                                destroyBanner();
                                Toast.makeText(mContext, s + ":" + s1, Toast.LENGTH_SHORT).show();
                                Log.e("openseterror", "code:" + s + "----message:" + s1);
                            }
                        });
                    }

                    @Override
                    public void onLoadFail(String s, String s1) {
                        Toast.makeText(mContext, s + s1, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void showInsert() {
        OSETInterstitial.getInstance()
                .setContext(mContext)
                .setPosId(Common.POS_ID_INTERSTITIAL)
                .loadAd(new OSETInterstitialAdLoadListener() {
                    @Override
                    public void onLoadSuccess(OSETInterstitialAd osetInterstitialAd) {
                        osetInterstitialAd.showAd(mContext, new OSETInterstitialListener() {
                            @Override
                            public void onShow() {
                                Toast.makeText(mContext, "onShow", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(String s, String s1) {
                                Toast.makeText(mContext, "onError", Toast.LENGTH_SHORT).show();
                                Log.e("openseterror", "code:" + s + "----message:" + s1);
                            }

                            @Override
                            public void onClick() {
                                Toast.makeText(mContext, "onClick", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onClose() {
                                Toast.makeText(mContext, "onClose", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onLoadFail(String s, String s1) {
                        Toast.makeText(mContext, s + s1, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //申请安卓11以上特殊危险权限
    private void requestManagerPermission() {
        //当系统在11及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 没文件管理权限时申请权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                startActivityForResult(intent, Constants.intent1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.intent1) {
            if (!Environment.isExternalStorageManager() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                requestManagerPermission();
            }
        }
    }

    //获取提交信息
    @Override
    public void getCommits(GiteeCommitsBean bean) {
        long appVersionCode = SystemUtils.getAppVersionCode(mContext);
        String content = bean.getContent();
        if (content == null) return;
        String s = SystemUtils.base64Decode(content, "UTF-8");
        Long l = main(s);
        if (l > appVersionCode) {//判断线上版本号是否大于本地版本号
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            alertDialog = builder.create();
            alertDialog.show();
            View inflate = LayoutInflater.from(mContext).inflate(R.layout.alertdialog_shengji, null);
            alertDialog.setContentView(inflate);
            alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            alertDialog.setCanceledOnTouchOutside(false);
            TextView mTvCancel = inflate.findViewById(R.id.tv_gengxincancel);
            TextView mTvGengXin = inflate.findViewById(R.id.tv_lijigengixn);
            TextView mTvtiShi = inflate.findViewById(R.id.shengjitishiyu);
            if (s.contains("强制")) {
                mTvtiShi.setText("本次升级为强制升级，请尽快完成升级，否则将影响您的使用体验");
                alertDialog.setCanceledOnTouchOutside(false);//点击屏幕其他地方不响应
                alertDialog.setCancelable(false);//禁用返回键
                mTvCancel.setVisibility(View.GONE);
            }
            //更新
            mTvGengXin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String down_url = Constants.uPData_Url;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        //是否有安装位置来源的权限
                        boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                        if (haveInstallPermission) {
                            Log.i("TAG", "8.0手机已经拥有安装未知来源应用的权限，直接安装！");
//                            Intent intent = new Intent(MainActivity.this, DownAPKService.class);
//                            intent.putExtra("apk_url", down_url);
//                            startService(intent);
                            DownLoad(down_url, "ttkl.apk");
                            alertDialog.dismiss();
                        } else {
                            Uri packageUri = Uri.parse("package:" + AppUtils.getAppPackageName());
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                            startActivityForResult(intent, 10086);
                        }
                    } else {
                        DownLoad(down_url, "ttkl.apk");
                        alertDialog.dismiss();
                    }
                }
            });
            //取消
            mTvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                }
            });
        }
    }

    public Long main(String str) {
        String startstr = "versionCode";
        int startIndex = str.indexOf(startstr) + startstr.length();
        String endstr = "versionName";
        int endIndex = str.indexOf(endstr);
        String result = str.substring(startIndex, endIndex);
        String replace = result.replaceAll("\\s+", "");
        Long l = Long.parseLong(replace);
        return l;
    }

    /**
     * 下载apk
     *
     * @param urlString
     * @param fileName
     */
    private ProgressDialog dialog;

    private void DownLoad(String urlString, String apkname) {
        dialog = HomeProgressDialog.getInstance(mContext);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMessage("正在下载，请稍后...");
        dialog.setCanceledOnTouchOutside(false);//点击屏幕其他地方不响应
        dialog.setCancelable(false);
        dialog.show();
        dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        dialog.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                uiOptions |= 0x00001000;
                dialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
            }
        });
        String path = mContext.getExternalFilesDir(null) + "/";
        OkHttpUtils.get(urlString)//
                .tag(this)//
                .execute(new DownloadFileCallBack(path, apkname));//保存到sd卡
    }

    private class DownloadFileCallBack extends FileCallback {
        public DownloadFileCallBack(String destFileDir, String destFileName) {
            super(destFileDir, destFileName);
        }

        @Override
        public void onBefore(BaseRequest request) {

        }

        @Override
        public void onResponse(boolean isFromCache, File file, Request request, Response response) {
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            if (file != null && file.exists()) {
//                installApk(file);
                installApkO(mContext, file.getPath());
                Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(mContext, "下载失败，请检查网络", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            System.out.println("downloadProgress -- " + totalSize + "  " + currentSize + "  " + progress + "  " + networkSpeed);
            if (dialog != null) {
                float allFloat = SystemUtils.getSize((int) totalSize);
                float curFloat = SystemUtils.getSize((int) currentSize);
                dialog.setProgressNumberFormat(String.format(Locale.CHINA, "%.2fMB/%.2fMB", curFloat, allFloat));
                dialog.setProgress((int) currentSize);
                dialog.setMax((int) totalSize);
            }
        }

        @Override
        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(isFromCache, call, response, e);
            Toast.makeText(mContext, "下载失败，请检查网络", Toast.LENGTH_SHORT).show();
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    }

    // 3.下载成功，开始安装,兼容8.0安装位置来源的权限
    private void installApkO(Context context, String downloadApkPath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //是否有安装位置来源的权限
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                Log.i("TAG", "8.0手机已经拥有安装未知来源应用的权限，直接安装！");
                installApk(context, downloadApkPath);
            } else {
                Uri packageUri = Uri.parse("package:" + AppUtils.getAppPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                startActivityForResult(intent, 10086);
            }
        } else {
            installApk(context, downloadApkPath);
        }
    }

    public void installApk(Context context, String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        Log.i("安装路径", "安装路径: " + downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, AppUtils.getAppPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyBanner();
    }
}